package com.softeem.mpdemo.controller;

import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.softeem.mpdemo.dto.Result;
import com.softeem.mpdemo.entity.Admin;
import com.softeem.mpdemo.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;

@RestController
public class AdminController {
    @Autowired
    private AdminService adminService;
//登录
    @RequestMapping("/admin/login")
    public Result login(Admin admin){

        return adminService.login(admin);
    }
//注册
    @RequestMapping("/admin/reg")
    public Result reg(Admin admin) {

        return adminService.reg(admin);
    }
    //修改密码 往后业务层也写在下面
    @RequestMapping("/admin/update")
    public Result modify(Admin admin){
        //判断是否需要修改密码
        if(Objects.nonNull(admin.getPassword())){
            //生成盐
            String salt = RandomUtil.randomString(6);
            //使用盐和输入密码加密
            String pwd = SecureUtil.md5(salt + admin.getPassword());
            //将新密码和随机盐添加到对象中
            admin.setPassword(pwd);
            admin.setSalt(salt);
        }
        //执行修改（根据id修改）
        if(adminService.updateById(admin)){
            return Result.ok().setMsg("修改成功").setData(admin);
        }
        return Result.fail().setMsg("更新失败");
    }


    /**
     * 管理员列表   132****345（脱敏）
     * @return
     */
    @RequestMapping("/admin/listAll")
    public Result selectAll(){
        //查询所有管理员
        List<Admin> list = adminService.list();
        if(list.isEmpty()){
            return Result.fail().setMsg("无记录");
        }
        list.forEach(admin -> {
            //取出密码、盐脱敏后重新填充到密码属性中
            admin.setPassword(DesensitizedUtil.password(admin.getPassword()));
            admin.setSalt(DesensitizedUtil.password(admin.getSalt()));
        });
        return Result.ok().setMsg("查询成功").setData(list);
    }
    /**
     * 根据id删除管理员(物理删除：谨慎操作)
     * @param id
     * @return
     */
    @RequestMapping("/admin/del")
    public Result delById(Integer id){
        Admin admin = adminService.getById(id);
        if(Objects.isNull(admin)){
            return Result.fail().setMsg("该管理员不存在或者已经被删除!");
        }
        if(adminService.removeById(id)){
            return Result.ok().setMsg("删除成功").setData(admin);
        }
        return Result.fail().setMsg("删除失败");
    }

}




